import { ref } from 'vue'
import { userApi } from '../api'

export function useTableList() {
  const tableData = ref([])
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const loading = ref(false)

  // 获取表格数据
  const getList = async () => {
    try {
      loading.value = true
      const res = await userApi.getList({
        page: pagination.value.current,
        limit: pagination.value.pageSize
      })
      tableData.value = res.data
      pagination.value.total = res.pagination.total
    } catch (error) {
      console.error('获取数据失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 处理分页变化
  const handlePageChange = (page) => {
    pagination.value.current = page
    getList()
  }

  // 处理每页条数变化
  const handleSizeChange = (size) => {
    pagination.value.pageSize = size
    pagination.value.current = 1
    getList()
  }

  // 删除用户
  const handleDelete = async (id) => {
    try {
      await userApi.delete(id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }

  // 创建用户
  const createUser = async (data) => {
    try {
      await userApi.create(data)
      ElMessage.success('创建成功')
      getList()
    } catch (error) {
      console.error('创建失败:', error)
    }
  }

  // 更新用户
  const updateUser = async (id, data) => {
    try {
      await userApi.update(id, data)
      ElMessage.success('更新成功')
      getList()
    } catch (error) {
      console.error('更新失败:', error)
    }
  }

  return {
    tableData,
    pagination,
    loading,
    getList,
    handlePageChange,
    handleSizeChange,
    handleDelete,
    createUser,
    updateUser
  }
}
